"""
@ProjectName : CourseManagementSystem
@File        : course_db.py
@Author      : WorldWind(1772830365@qq.com)
@Address     : ChangSha - BoWeiFeng
@Date        : 2025/7/17 下午1:35
"""
from utils.DBUtils import DataBase
from courses.course import Course


# 数据库业务实现类
class CourseDB:
    def __init__(self):
        host = '127.0.0.1'
        port = 3306
        user = 'root'
        passwd = 'root'
        db = 'course'
        self.dbObj, self.curser = DataBase.opemDB(host, port, user, passwd, db)
        print(f'This is __init__ method. {self.get_class_name()} class startup')

    def add(self, course):
        sql = f"INSERT INTO t_course(course_no,course_name,max_score,min_sorce) VALUES ('{course.course_no}','{course.course_name}',{course.max_score},{course.min_sorce})"
        record = DataBase.writeDB(sql, self.curser)
        self.dbObj.commit()
        return record

    def delete(self, id):
        sql = f"DELETE FROM t_course WHERE id = {id}"
        record = DataBase.writeDB(sql, self.curser)
        self.dbObj.commit()
        return record

    def update(self, course):
        sql = f"UPDATE t_course SET course_no = '{course.course_no}',course_name = '{course.course_name}',max_score={course.max_score},min_sorce={course.min_sorce} WHERE id = {course.id}"
        record = DataBase.writeDB(sql, self.curser)
        self.dbObj.commit()
        return record

    # 查询所有课程
    def searchAllCourses(self):
        sql = 'SELECT * FROM t_course'
        result = DataBase.readAll(sql, self.curser)
        return result

    # 根据课程名称进行模糊查询
    def searchByCoursename(self, course_name=None):
        sql = f"SELECT * FROM t_course WHERE course_name LIKE '%{course_name}%'"
        result = DataBase.readAll(sql, self.curser)
        return result

    @classmethod
    def get_class_name(cls):
        return cls.__name__

    def __del__(self):
        print(f'This is __del__ method. The {self.get_class_name()} class has been recycled')


if __name__ == '__main__':
    c = CourseDB()
    # course = Course('c008','数据库',100,60)
    # print(c.add(course))
    # course = Course()
    # course.course_no = 'c001'
    # course.course_name = '计算机组成原理'
    # course.max_score = 100
    # course.min_sorce = 60
    # course.id = 1
    # print(c.update(course))
    # res = c.searchAllCourses()
    # print(res[0]['course_name'])
    # res = c.searchByCoursename('原理')
    # print(res)
